package com.ruoyi.extdata.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.ruoyi.common.config.AwsConfig;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.AwsUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.DownloadUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.extdata.config.DFSConfig;
import com.ruoyi.extdata.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.TempFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * 文件服务
 *
 * @Author: Jamnsin
 * @Date: 2020/2/11 4:45 下午
 */
@Slf4j
@Service
public class FileServiceImpl implements IFileService {

    @Autowired
    DFSConfig dfsConfig;

    @Autowired
    FastFileStorageClient fastFileStorageClient;

    @Autowired
    AwsConfig awsConfig;

    @Override
    public String uploadLocalServer(MultipartFile mFile) {
        String uploadPath = RuoYiConfig.getUploadPath();
        String filePath = null;
        try {
            filePath = FileUploadUtils.upload(uploadPath, mFile);
            log.info("上传本地服务器路径，filePath = {}", filePath);
        } catch (IOException e) {
            log.error("uploadLocalServer error", e);
            throw new BusinessException(RspEnmu.FILE_UPLOAD_FAIL, e.getMessage());
        }

        File file = new File(filePath);
        if (!file.exists()) {
            throw new BusinessException(RspEnmu.FILE_UPLOAD_ERR);
        }

        return filePath;
    }

    @Override
    public String uploadFdfsServer(String filePath, String fileExtension) {
        File tmpFile = new File(filePath);
        try (InputStream in = new FileInputStream(tmpFile)) {

            StorePath storePath = fastFileStorageClient.uploadFile(in, tmpFile.length(), fileExtension, null);
            log.info("图片上传返结果：storePath = {}", storePath);

            // 生成图片地址
            String fullPath = storePath.getFullPath();
            log.info("远程图片路径：remoteFilePath = {}", fullPath);

            if (StringUtils.isEmpty(fullPath)) {
                throw new BusinessException(RspEnmu.FILE_UPLOAD_ERR, "文件上传远程服务器返回文件路径为空");
            }

            return fullPath;
        } catch (IOException e) {
            throw new BusinessException(RspEnmu.FILE_UPLOAD_ERR, e.getMessage());
        }
    }

    @Override
    public void remoteDownload(File file, String remoteUrl) {
        String remoteFileUrl = dfsConfig.getBaseUrl() + remoteUrl;
        DownloadUtils.remoteDownload(file, remoteFileUrl);
    }

    @Override
    public String createJsonFileToServer(JSONObject jsonObject) {
        log.info("保存文件服务器");
        File tempFile = null;
        try {
            tempFile = File.createTempFile("temp", ".json");
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tempFile));
            bufferedWriter.write(jsonObject.toJSONString());
            bufferedWriter.close();
            return uploadFdfsServer(tempFile.getPath(), "json");
        } catch (IOException e) {
            log.error("createJsonFileToServer error", e);
        }finally {
            if (tempFile != null){
                tempFile.delete();
            }
        }
        return "";
    }

    /**
     * 上传至aws
     * @param jsonObject
     * @param Path
     * @return
     */
    @Override
    public String createJsonFile(JSONObject jsonObject,String Path) {
        log.info("保存文件服务器");
        File tempFile = null;
        try {
            tempFile = File.createTempFile("temp", ".json");
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tempFile));
            bufferedWriter.write(jsonObject.toJSONString());
            bufferedWriter.close();
            //调用AWS上传工具类上传文件
            Date date = new Date();
            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy/MM/dd");
            String key = null;
            if("crs".equals(Path)){
                key = AwsConfig.getCrsPath() + dateFormat.format(date);
            }else {
                key = AwsConfig.getXdsPath() + dateFormat.format(date);
            }
            URL url = AwsUtil.uploadObject(AwsConfig.getBucketName(), key +"/"+ tempFile.getName(), tempFile.getPath());
            log.info(String.valueOf(url));
            return String.valueOf(url);
        } catch (IOException e) {
            log.error("createJsonFile error", e);
        }finally {
            if (tempFile != null){
                tempFile.delete();
            }
        }
        return "";
    }


}
